package com.csthink.mr.serial;

import org.apache.hadoop.io.Writable;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * @author <a href="mailto:security.2009@live.cn">dumingyang</a>
 * @since 2024-04-13 20:48
 */
public class HadoopSerialize {

    public static void main(String[] args) throws IOException {
        StudentWritable studentWritable = new StudentWritable(1, "student", 18, 190.0);

        // 将 Student 对象序列化到文件中
        FileOutputStream fos = new FileOutputStream("out/student_hadoop.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        studentWritable.write(oos);
        oos.close();
        fos.close();
    }
}

class StudentWritable implements Writable {

    private int id;
    private String name;
    private int age;
    private double salary;

    @Override
    public void write(java.io.DataOutput out) throws IOException {
        out.writeLong(id);
        out.writeUTF(name);
        out.writeInt(age);
        out.writeDouble(salary);
    }

    @Override
    public void readFields(java.io.DataInput in) throws IOException {
        id = in.readInt();
        name = in.readUTF();
        age = in.readInt();
        salary = in.readDouble();
    }

    public StudentWritable() {
    }

    public StudentWritable(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "StudentWritable{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}
